package stack;

public class MyStack {
	public static void main(String[] args) {
		ArrayStack arrayStack = new ArrayStack(4);
		arrayStack.push(1);
		arrayStack.push(2);
		arrayStack.push(3);
		arrayStack.push(4);
		arrayStack.list();
		System.out.println(arrayStack.pop());
		arrayStack.list();
		System.out.println(arrayStack.peek());
	}
}

class ArrayStack {
	private int maxSize;//栈的大小
	private int[] stack;//数组，模拟栈，存储数据
	private int top = -1;//栈顶

	public ArrayStack(int maxSize) {
		this.maxSize = maxSize;
		stack = new int[this.maxSize];
	}

	//判断是否满
	public boolean isFull() {
		return top == maxSize - 1;
	}

	//栈空
	public boolean isEmpty() {
		return top == -1;
	}

	//入栈
	public void push(int value) {
		//判断是否满
		if (isFull()) {
			System.out.println("栈满");
			return;
		}
		top++;

		stack[top] = value;
	}

	//出栈
	public int pop() {
		if (isEmpty()) {
			//抛出异常
			throw new RuntimeException("栈空");
		}
		int value = stack[top];
		top--;
		return value;
	}

	//遍历栈,需要从栈顶开始
	public void list() {
		if (isEmpty()) {
			throw new RuntimeException("栈空");
		}
		for (int i = top; i >= 0; i--) {
			System.out.println("stack[" + i + "]=" + stack[i]);
		}
	}

	public int peek() {
		return stack[top];
	}
}
